package com.foreveross.taskservice.engine.worker;

import java.util.List;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.foreveross.taskservice.common.CacheDataSpace;
import com.foreveross.taskservice.common.TaskStatusEnum;
import com.foreveross.taskservice.core.domain.channel.GradChannelEntity;
import com.foreveross.taskservice.infra.cfg.PropertyUtils;
import com.foreveross.taskservice.infra.cfg.taskservice.TaskServicePropertiesLoader;
/**
 * 任务补偿，将失败的任务重新加载到等待队列
 * @author Administrator
 *
 */
public class TaskCompensationWorker extends AbstractTaskStatefulJobWorker{

	@Override
	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		long stime = System.currentTimeMillis();
		log.info("任务补偿TaskCompensationWorker开始....");
		List<GradChannelEntity> channels;
		CacheDataSpace space=CacheDataSpace.AirFreightSpace();
		try {
			int size=PropertyUtils.getIntProperty("taskservice.task.compensation.maxsize", TaskServicePropertiesLoader.FILE_NAME,1);
			if(size<=1){ //统一控制，小于2时，不进行补偿
				return;
			}
			int way=PropertyUtils.getIntProperty("taskservice.task.compensation.way", TaskServicePropertiesLoader.FILE_NAME,1);
			channels=getGradChannelApplication().getEnableChannel();
	
				
				if(channels!=null && !channels.isEmpty()){
					if(way == 1){
						for(GradChannelEntity c:channels){
							this.reloadCompensation(c.getId(), c.getTaskCompensateSize());
						}
					}else if(way == 2){
						for(GradChannelEntity c:channels){
							//后补偿策略，先要判断任务等待中的是不是为0
								long waiting = getTaskCacheQuery().queryTaskSize(space, c.getId(), TaskStatusEnum.TASK_WATI);
								if(waiting <= 0){ //只有为0了才启动补偿
									this.reloadCompensation(c.getId(), c.getTaskCompensateSize());
								}
						}
					}
					
				}
			
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}finally{
			log.info("任务补偿TaskCompensationWorker结束....耗时ms:"+(System.currentTimeMillis()-stime));
			channels=null;
		}
	}

	private void reloadCompensation(long channelId, int compensateSize) throws Exception{
		getTaskCacheStorage().reloadCompensation(CacheDataSpace.AirFreightSpace(),channelId,compensateSize ,TaskStatusEnum.TASK_FETCH_FAIL);
		getTaskCacheStorage().reloadCompensation(CacheDataSpace.AirFreightSpace(),channelId,compensateSize ,TaskStatusEnum.TASK_PARSE_FAIL);
		getTaskCacheStorage().reloadCompensation(CacheDataSpace.AirFreightSpace(),channelId,compensateSize ,TaskStatusEnum.TASK_OTHER_FAIL);
		//getTaskCacheStorage().reloadCompensation(CacheDataSpace.AirFreightSpace(),c.getId(),size ,TaskStatusEnum.TASK_UNKOWN_STATUS);
	}
}
